package intranet.controllers;
import org.springframework.web.servlet.ModelAndView;

import intranet.addon.Encryption;
import intranet.models.*;
import intranet.tools.*;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewFileController extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/* IsNumber Function */
	public static boolean IsNumber(String num) {
        try {
            Integer.parseInt(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
		//my New ViewAllfile (da)
		
		@RequestMapping("/view_all_files.html")
		public ModelAndView ViewAllFiles(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{		
			ModelAndView mv=new ModelAndView("index");
			if(session.getAttribute("user_id")!=null){	
				String page= request.getParameter("page");
				String cat_id=request.getParameter("txtcat");
				int catid=0;
				if (cat_id!=null)
				catid =Integer.parseInt(cat_id);
				int user_id=Integer.parseInt(session.getAttribute("user_id").toString());
					ViewAllFileModel fileModel=new ViewAllFileModel();
					ResultSet rs=fileModel.ViewAllFiles(catid,user_id);
					ArrayList List=this.resultSetToArrayList(rs);
					int RowCount=List.size();
					FileCategoryModel Fcg=new FileCategoryModel();
					mv.addObject("includethispage", "file_sharing/viewallfiles/ViewAllFile.jsp");
					mv.addObject("curcategory",catid);
					mv.addObject("data", List);
					ResultSet rscat=Fcg.SelectFileCategory(0);
					ArrayList cat=this.resultSetToArrayList(rscat);
					mv.addObject("categories",cat);
					page=(page==null || IsNumber(page)==false)?"1":page;
					// Pagination Link Elements
					int PageSize=15;
					int PageCount=((RowCount%PageSize)>0)?Math.round(RowCount/PageSize)+1:Math.round(RowCount/PageSize);
					page=(Integer.parseInt(page)<=0 ||Integer.parseInt(page)>PageCount)?"1":page;
					int StartingRow=(Integer.parseInt(page)-1)*PageSize;
					int EndingRow=(Integer.parseInt(page)*PageSize)-1;
					mv.addObject("page", page);
					mv.addObject("PageCount", PageCount);
					mv.addObject("StartingRow", StartingRow);
					mv.addObject("EndingRow", EndingRow);
					
					//Send ServerURL
					WebConfig conf=new WebConfig();
					mv.addObject("ServerURL",conf.getURL());
			}else{
				response.sendRedirect("login.html");
			}
			return mv;
		}
		//Search AllFile
		
			//Search AllFile
			
	@RequestMapping("/search_files.html")
		public ModelAndView SearchAllFile(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
			ModelAndView mv=new ModelAndView("index");
			if(session.getAttribute("user_id")!=null){		
				String page= request.getParameter("page");
				String cat_id=request.getParameter("txtcat");
				String key_word=request.getParameter("txtkeyword");
				int catid=0;
				if (cat_id!=null)
				catid =Integer.parseInt(cat_id);
					SearchFilesModel smodel=new SearchFilesModel();
					ResultSet rs=smodel.SearchFiles(catid,key_word);
					//return result
					ArrayList List=this.resultSetToArrayList(rs);
					int RowCount=List.size();
					FileCategoryModel Fcg=new FileCategoryModel();
					mv.addObject("includethispage", "search_files.jsp");
					mv.addObject("cat_id",catid);
					mv.addObject("data", List);
					ResultSet rscat=Fcg.SelectFileCategory(0);
					ArrayList cat=this.resultSetToArrayList(rscat);
					mv.addObject("categories",cat);
					page=(page==null || IsNumber(page)==false)?"1":page;
					// Pagination Link Elements
					int PageSize=3;
					int PageCount=((RowCount%PageSize)>0)?Math.round(RowCount/PageSize)+1:Math.round(RowCount/PageSize);
					page=(Integer.parseInt(page)<=0 ||Integer.parseInt(page)>PageCount)?"1":page;
					int StartingRow=(Integer.parseInt(page)-1)*PageSize;
					int EndingRow=(Integer.parseInt(page)*PageSize)-1;
					mv.addObject("page", page);
					mv.addObject("PageCount", PageCount);
					mv.addObject("StartingRow", StartingRow);
					mv.addObject("EndingRow", EndingRow);
					WebConfig conf=new WebConfig();
					mv.addObject("ServerURL",conf.getURL());
			}else{
				response.sendRedirect("login.html");
			}
			return mv;
		
		}

		@RequestMapping("/view_file_detail.html")
		public ModelAndView ViewAllFile(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{		
			ModelAndView mv=new ModelAndView("index");
			if(session.getAttribute("user_id")!=null){
				String file_id= request.getParameter("file_id");
				file_id=(file_id==null || IsNumber(file_id)==false)?"0":file_id;
				file_id=(Integer.parseInt(file_id)<=0)?"0":file_id;
				/* IF Requested ID=0 */
				if(Integer.parseInt(file_id)==0){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}else{
					MyuploadModel Myupload=new MyuploadModel();
					// Verify File Member
					/*if(Myupload.isOwner(Integer.parseInt((String)session.getAttribute("user_id")), Integer.parseInt(file_id))==false){
						mv.addObject("includethispage", "not_accessible_page.jsp");
						return mv;
					}*/
					FileCategoryModel CategoryModel=new FileCategoryModel();
					ResultSet rs=Myupload.SelectUploadedFile(Integer.parseInt(file_id));
					ResultSet rscat=CategoryModel.SelectFileCategory(0);
					ArrayList Myuploads=this.resultSetToArrayList(rs);
					ArrayList FileCategories=this.resultSetToArrayList(rscat);
					
					//Passing User and Group Shared
					ResultSet rsuser=Myupload.SelectUsersShared(Integer.parseInt(file_id));
					ResultSet rsgroup=Myupload.SelectGroupsShared(Integer.parseInt(file_id));
					ArrayList userList=this.resultSetToArrayList(rsuser);
					ArrayList groupList=this.resultSetToArrayList(rsgroup);
					mv.addObject("userlist", userList);
					mv.addObject("grouplist", groupList);
					
					//Passing Page Included
					mv.addObject("includethispage", "file_sharing/viewallfiles/ViewFileDetail.jsp");
					// Passing Data Record & Image_File
					mv.addObject("data", Myuploads);
					// Passing ALL FILE CATEGORIES
					mv.addObject("categories", FileCategories);
					// Passing file id
					String keywords=Myupload.SelectFileKeywords(Integer.parseInt(file_id));
					mv.addObject("keywords",keywords);
					// Passing Web URL
					WebConfig con=new WebConfig();
					String URL=con.getURL();
					mv.addObject("weburl",URL);
					return mv;
				}
			}else{
				response.sendRedirect("login.html");
			}
			return mv;
		}
		
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
		    for(int i=1; i<=columns; i++){
		    row.put(md.getColumnName(i),rs.getObject(i));
		    }
		    }
		    return results;

	    }
}